package com.zf.websocket.endpoint;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简单群聊系统
 *
 * @author Zhou Feng
 */
@Slf4j
@Component
@ServerEndpoint(value = "/chat")
public class ChatEndpoint {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final ConcurrentHashMap<String, ChatEndpoint> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketMap.put(session.getId(), this);
    }

    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        for (ChatEndpoint webSocketServer : webSocketMap.values()) {
            if (this == webSocketServer) {
                // 回显消息给自己
                webSocketServer.session.getAsyncRemote().sendText("[我] " + message);
            } else {
                //发送给其他在线用户
                // 异步发送
                webSocketServer.session.getAsyncRemote().sendText(String.format("[%s] %s", session.getId(), message));
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.getMessage());
    }

}
